import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance创建axios实例
const service = axios.create({
  // 基地址
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // 请求超时的时间
  timeout: 5000 // request timeout
})

// request interceptor请求拦截器
service.interceptors.request.use(
  config => {
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      return response.data
    } else {
      console.log(response)
      return Promise.reject(new Error(response.data.message))
    }
  },
  // 只要返回4开头的，都会走error
  error => {
    if (error.response.data.code === 10002) {
      store.dispatch('user/doLogout')
      // router.currentRoute===>this.$route
      router.push('/login?return_url=' + router.currentRoute.path)
    }
  }
)
export default service

